//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using Content = CommunityServer.Components.Content;

namespace CommunityServer.Controls
{
    /// <summary>
	/// A ContentPart loads content from the database 
	/// (much simplified from CMS, more can be moved here later)
	/// </summary>
	[PersistChildren(true)]
	[ParseChildren(false)]
	public class ContentPart : WebControl, IText
	{
		private CommunityServer.Components.Content _content = null;
		private string _name = null, _text = null, _qlList = null, _tip = null;
		private int _id = 0, width=640, height=510;
		private bool _editoronly = false;

		public ContentPart() : base(HtmlTextWriterTag.Div)
		{
		}

		#region overridden methods
		protected override void OnLoad(EventArgs e)
		{
            
			if (CanUserEdit())
			{
				JavaScript.RegisterRefresh(Page);
				Page.RegisterClientScriptBlock(this.GetType().Name + "EditContent", BuildEditContentScript());
				JavaScript.RegisterToolTips(this.Page);
			} 

			base.OnLoad (e);
		}

		protected override void AddParsedSubObject(object obj)
		{
			if (!Content.Exists && Globals.IsNullorEmpty(Text) && (!_editoronly || CanUserEdit()))
				base.AddParsedSubObject (obj);
		}

        protected override void OnPreRender(EventArgs e)
        {
            if (Globals.IsNullorEmpty(this.ID))
                this.ID = "ContentPart";

            base.OnPreRender(e);
        }

		protected override void RenderContents(HtmlTextWriter writer) 
		{
			// can we edit? if so, output a div
			if (CanUserEdit())
			{
				// now add another div for our style swapping
				writer.WriteBeginTag("div");
				writer.WriteAttribute("onmouseover", "ShowEditBlock(this)");
				writer.WriteAttribute("onmouseout", "HideEditBlock(this)");
				writer.WriteAttribute("class", "CommonContentPartBorderOff");
				writer.Write(HtmlTextWriter.TagRightChar);
				
				writer.WriteBeginTag("div");
				writer.WriteAttribute("id", this.ClientID);
				string tip = _tip;
				if (tip == null)
					tip = ResourceManager.GetString("ContentPart_Hover");

				writer.WriteAttribute("onmouseover", JavaScript.ToolTipText(tip,160));
				writer.WriteAttribute("ondblclick", string.Format("{3}.showEditContent({0},'{1}','{2}');", Content.ID, Content.Name, this.EditDefaultConent ? this.ClientID : "", this.GetType().Name));
				writer.Write(HtmlTextWriter.TagRightChar);
			}

			if (Content.Exists)	
			{
				writer.Write(Content.RenderedBody(PostTarget.Web));
			}
			else
			{
				// shall we show the Text property instead?
				if (!Globals.IsNullorEmpty(Text) && (!_editoronly || CanUserEdit()))
					writer.Write(Text);
				else
					base.RenderContents(writer);
			}

			if (CanUserEdit())
			{
				writer.WriteEndTag("div");
				writer.WriteEndTag("div");
			}
		}

        protected virtual bool CanUserEdit()
        {
            return CSContext.Current.User.IsAdministrator;
        }

        protected virtual string EditUrl()
        {
            return Contents.EditContentUrl();
        }

		protected string BuildEditContentScript()
		{
			StringBuilder sb = new StringBuilder();
			sb.AppendFormat(@"<script type=""text/javascript"">{0}", Environment.NewLine);
            sb.AppendFormat("var {0} = {{ {1}", this.GetType().Name,Environment.NewLine);
			sb.AppendFormat("\"showEditContent\": function(contentID,contentName,clientID) {{{0}", Environment.NewLine);
			sb.AppendFormat(@" Telligent_Modal.Open('{0}?contentid=' + contentID + '&contentname=' + contentName + '&clientid=' + encodeURIComponent(clientID)", EditUrl());
			sb.AppendFormat(@",{0},{1},refresh); {2}", width, height, Environment.NewLine);
			sb.AppendFormat(@"}}{0}", Environment.NewLine);
            sb.AppendFormat(@"}}{0}", Environment.NewLine);
			sb.AppendFormat(@"</script>{0}", Environment.NewLine);
			return sb.ToString();
		}
		#endregion

		#region Properties
		protected Content Content
		{
			get 
			{
				if (_content == null)
				{
                    if (ContentID == 0)
						_content = Contents.GetContent(ComputeContentName());
					else
						_content = Contents.GetContent(ContentID,true);

                    if(_content == null)
                    {
                        _content = new Content();
                        _content.Name = ComputeContentName();
                    }
				}

				return _content;
			}
		}

        protected virtual string ComputeContentName()
        {
            if(Globals.IsNullorEmpty(QueryString))
                return ContentName;

            string[] sa = QueryString.Split(',');
            string returnValue = ContentName;
            foreach(string key in sa)
            {
                returnValue = string.Format("{0}:{1}:{2}", returnValue,key,Context.Request.QueryString[key]);
            }

            return returnValue;
        }

		/// <summary>
		///  the content to display from database, by name
		/// </summary>
        public virtual string ContentName
		{
			get {return _name;}
			set {_name = value;}
		}

        public string QueryString
        {
            get{return _qlList;}
            set{_qlList = value;}
        }

		/// <summary>
		///  the content to display from database, by id
		/// </summary>
		public int ContentID
		{
			get {return _id;}
			set {_id = value;}
		}

		/// <summary>
		/// Set true to hide default content from users
		/// that cannot edit the content
		/// </summary>
		public bool DefaultContentForEditorOnly
		{
			get {return _editoronly;}
			set {_editoronly = value;}
		}

        private bool _editDefault = true;

        public bool EditDefaultConent
        {
            get {return _editDefault;}
            set {_editDefault = value;}
        }


		/// <summary>
		/// take content ID/name from querystring if true
		/// </summary>
		public bool FromQueryString
		{
			set 
			{
				if (value == true)
				{
					ContentID = Globals.SafeInt(Context.Request.QueryString["contentid"], 0);

					if (ContentID == 0)
						ContentName = Context.Request.QueryString["contentname"];
				}
			}
		}

		public int ModalHeight
		{
			get {return height;}
			set {height = value;}
		}

		public string Text
		{
			get {return _text;}
			set {_text = value;}
		}

		public string Tip
		{
			get {return _tip;}
			set {_tip = value;}
		}

		public int ModalWidth
		{
			get {return width;}
			set {width = value;}
		}
#endregion

		#region IText Members
		public Control Control
		{
			get {return this;}
		}

		#endregion
	}
}
